package org.chispa.api.parsers;

import java.util.NoSuchElementException;
import java.util.Scanner;

import org.chispa.api.util.BadSyntaxException;
import org.chispa.api.util.ExpressionLanguage;
import org.chispa.api.util.NoSuitableVisitorException;

public abstract class ParserState {
	
	protected StringBuilder buffer;
	protected Scanner scan;
	protected ParserListener<?> listener;
	protected StateRepository repo=StateRepository.getInstance();
	
	protected ParserState(Scanner scan,StringBuilder _buffer)
	{
		this.scan=scan;
		buffer=_buffer;
	}
	
	protected ParserState(Scanner scan)
	{
		this(scan,new StringBuilder());
	}
	
	protected void append(String text)
	{
		buffer.append(" "+text);
	}
	
	public String flush()
	{
		String val=get();
		buffer=new StringBuilder();
		return val;
	}
	
	private String get()
	{
		if(buffer!=null)
		{
			String toRet=buffer.toString().trim();
			return toRet;
		}
		return null;
	}
	
	protected boolean isUnclosedLiteral(String text)
	{
		return ExpressionLanguage.isUnclosedLiteral(text);
	}
	
	public void setListener(ParserListener<?> listener)
	{
		this.listener=listener;
	}
	
	public ParserState validateState() throws NoSuchElementException, BadSyntaxException, NoSuitableVisitorException {
		if(scan.hasNext()){
			String text=scan.next();
			return validateState(text);
		}
		return this;
	}	
	
	protected ParserState validateState(String text) throws NoSuchElementException, BadSyntaxException, NoSuitableVisitorException {
		append(text);
		return validateState();
	}
	
	protected void setBuffer(StringBuilder buffer)
	{
		this.buffer=buffer;
	}
}
